package com.leyou.auth.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetails;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.crypto.SecretKey;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.leyou.auth.constants.RedisConstants.JTI_KEY_PREFIX;
import static com.leyou.auth.constants.RedisConstants.TOKEN_EXPIRE_SECONDS;

/**
 * @author 虎哥
 */
public class JwtUtils {

    /**
     * JWT解析器
     */
    private final JwtParser jwtParser;
    /**
     * 秘钥
     */
    private final SecretKey secretKey;
    private final StringRedisTemplate redisTemplate;

    private final static ObjectMapper mapper = new ObjectMapper();

    public JwtUtils(String key, StringRedisTemplate redisTemplate) {
        // 生成秘钥
        secretKey = Keys.hmacShaKeyFor(key.getBytes(Charset.forName("UTF-8")));
        this.redisTemplate = redisTemplate;
        // JWT解析器
        this.jwtParser = Jwts.parserBuilder().setSigningKey(secretKey).build();
    }

    /**
     * 生成jwt，用默认的JTI
     *
     * @param userDetails 用户信息
     * @return JWT
     */
    public String createJwt(UserDetails userDetails) {
        return createJwt(userDetails, TOKEN_EXPIRE_SECONDS);
    }

    /**
     * 生成jwt，自己指定的过期时间
     *
     * @param userDetails 用户信息
     * @return JWT
     */
    public String createJwt(UserDetails userDetails, int expireSeconds) {
        try {
            // 获取JTI
            String jti = createJti();
            // 生成token
            String jwt = Jwts.builder().signWith(secretKey)
                    .setId(jti)
                    .claim("user", mapper.writeValueAsString(userDetails))
                    .compact();
            // 把jti存入redis，设置有效期
            redisTemplate.opsForValue().set(JTI_KEY_PREFIX + userDetails.getId(), jti, expireSeconds, TimeUnit.SECONDS);
            return jwt;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 解析jwt，并将用户信息转为指定的Clazz类型
     *
     * @param jwt token
     * @return 载荷，包含JTI和用户信息
     */
    public Payload parseJwt(String jwt) {

        // 1.解析jwt
        Jws<Claims> claimsJws = jwtParser.parseClaimsJws(jwt);
        Claims claims = claimsJws.getBody();
        // 2.获取用户
        UserDetails userDetails = null;
        try {
            userDetails = mapper.readValue(claims.get("user", String.class), UserDetails.class);
        } catch (IOException e) {
            throw new RuntimeException("解析用户失败！");
        }
        // 2.验证redis中的jti
        String cacheJTI = redisTemplate.opsForValue().get(JTI_KEY_PREFIX + userDetails.getId());
        // 2.1.非空验证，验证是否过期
        if (cacheJTI == null) {
            // 登录过期
            throw new RuntimeException("登录已经过期");
        }
        // 2.2.验证redis中的jti与用户jwt中的jti是否相等
        if (!StringUtils.equals(cacheJTI, claims.getId())) {
            // jti不匹配，应该是有其他人登录了
            throw new RuntimeException("账号在其它设备登录！");
        }
        // 3.封装payload并返回
        Payload payload = new Payload();
        payload.setJti(claims.getId());
        payload.setUserDetail(userDetails);
        return payload;
    }

    /**
     * 刷新jwt有效期
     * @param userId 用户id
     */
    public void refreshJwt(Long userId){
        redisTemplate.expire(JTI_KEY_PREFIX + userId, TOKEN_EXPIRE_SECONDS, TimeUnit.SECONDS);
    }
    /**
     * 刷新jwt有效期
     * @param userId 用户id
     * @param expireSeconds 过期时间
     */
    public void refreshJwt(Long userId, int expireSeconds){
        redisTemplate.expire(JTI_KEY_PREFIX + userId, expireSeconds, TimeUnit.SECONDS);
    }

    private String createJti() {
        return StringUtils.replace(UUID.randomUUID().toString(), "-", "");
    }
}